package ru.spb.osll.myfit.server.templateloader;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.common.TableStyle;
import ru.spb.osll.myfit.server.parser.PageParserUtils;
import ru.spb.osll.myfit.server.parser.TableElementParser;
import ru.spb.osll.myfit.wikiverifier.iterator.FileSystemIterator;
import util.GracefulNamer;

public class WikiTableTemplateLoader implements TableTemplateLoader {
	private TableTemplateLoader m_parentLoader;
	private HashMap<String, Vector<String>> m_templates;
	private Map<String, Class<?>> m_fixtures;

	public WikiTableTemplateLoader(String fixturesDirectory,
			TableTemplateLoader parentLoader) {
		m_parentLoader = parentLoader;
		TemplateLoaderFSIteratorListener listener = new TemplateLoaderFSIteratorListener();
		FileSystemIterator iterator = new FileSystemIterator(fixturesDirectory,
				listener);
		iterator.iterate();
		m_templates = listener.getTemplates();
		m_fixtures = m_parentLoader.getFixtureClasses();
	}

	@Override
	public Map<String, Class<?>> getFixtureClasses() {
		return m_fixtures;
	}

	@Override
	public Vector<String> getTemplate(String name) {
		Vector<String> rawTable = null;

		if (m_templates.containsKey(name)) {
			rawTable = m_templates.get(name);
		} else {
			rawTable = m_parentLoader.getTemplate(name);
		}

		return rawTable;
	}

	public Page saveTemplates() {
		TableElementParser parser = new TableElementParser();
		Page page = new Page();

		for (Vector<String> rawTable : m_templates.values()) {
			Table table = parser.parseTable(rawTable);
			table.setStyle(PageParserUtils
					.getTableStyle(getFixtureClass(table)));
			if (!table.getStyle().equals(TableStyle.UNKNOWN_FIXTURE)) {
				page.getElements().add(table);
			}
		}

		return page;
	}

	private Class<?> getFixtureClass(Table table) {
		Iterator<Vector<TableCell>> tableIter = table.getData().iterator();

		if (!tableIter.hasNext()) {
			return null;
		}

		Vector<TableCell> line = tableIter.next();
		String className = getClassName(line);
		if (m_fixtures.containsKey(className + "Fixture")) {
			className = className + "Fixture";
		}

		if (!m_fixtures.containsKey(className)) {
			return null;
		}

		return m_fixtures.get(className);
	}

	private String getClassName(Vector<TableCell> tableLine) {
		return GracefulNamer.disgrace(tableLine.get(0).getText());
	}
}
